// axios 二次封装
import Axios from 'axios'
import encConfig from './env'
import {
  Message
} from 'element-ui'
import router from 'vue-router'
import NProgress from 'nprogress'

// 创建axios实例
const service = Axios.create({
  baseURL: encConfig.prod.baseURL,
  timeout: 5000
})

// 创建请求拦截器 
service.interceptors.request.use(
  (config) => {
    NProgress.start();
    // 获取token
    if (config.url !== '/login') {
      const token = sessionStorage.getItem('token')
      token && (config.headers.Authorization = token)
      // Authorization 授权
    }
    return config
  }, error => {
    return Promise.reject(error)
  })

// 创建响应拦截器
service.interceptors.response.use(res => {
  // console.log('响应拦截器:', res);
  NProgress.done();
  const {
    meta: {
      msg,
      status: code
    },
    data: result
  } = res.data

  // 成功的
  const successCodeArr = [200, 201, 204]
  if (successCodeArr.includes(code)) {
    Message({
      message: msg,
      type: 'success'
    })

    // 成功了
    if (res.config.url === '/login') {
      sessionStorage.setItem('token', result.token)
    }

    return result
  }

  Message({
    message: msg,
    type: 'error'
  })

  // 无效token   无效都跳回 登陆页
  if (msg === '无效token') {
    router.replace('/login')
  }

  return Promise.reject(msg)
}, (error) => {
  return Promise.reject(error)
})
export default service
